/* eslint-disable no-console */
const axios = require('axios')

const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml') // 引入js-yaml库

// 获取当前脚本所在目录的上级目录
const parentDir = path.dirname(__dirname)
const configFilePath = path.join(parentDir, 'local_config.yaml')
// 读取YAML配置文件
const configData = fs.readFileSync(configFilePath, 'utf8')
const config = yaml.safeLoad(configData) // 使用js-yaml的safeLoad方法解析YAML字符串

// 查找用户ID
async function getUserIdByUsername(username) {
  if (username === 'admin') {
    username = 'root'
  }
  const encodedUsername = encodeURIComponent(username)
  const url = `http://git.mengning.com.cn/api/v4/users?username=${encodedUsername}`
  const headers = {
    'Private-Token': config.gitlab.token,
  }
  const response = await axios.get(url, { headers })
  const users = response.data
  if (users.length > 0) {
    const userId = users[0].id
    return userId // 返回用户ID
  }
  return ''
}

// 获取项目
const getUserProjects = async ctx => {
  const workspace = ctx.params.workspace
  const regex = /^([^-]+)-workspace$/
  if (!workspace.match(regex)) {
    ctx.body = {
      items: [], // 空的 items 数组
      error: 'workspace格式错误', // 错误信息
      totalItems: 0, // 总数为 0
    }
    return
  }
  const username = workspace.match(regex)[1]
  const userId = await getUserIdByUsername(username)
  if (!userId) {
    ctx.body = {
      items: [], // 空的 items 数组
      error: '找不到用户Id', // 错误信息
      totalItems: 0, // 总数为 0
    }
    return
  }

  const url = `http://git.mengning.com.cn/api/v4/users/${userId}/projects`
  const headers = {
    'Private-Token': config.gitlab.token,
  }

  const response = await axios.get(url, { headers })
  // 将项目列表写入ctx
  const items = response.data.map(item => ({
    apiVersion: 'devops.kubesphere.io/v1alpha3',
    kind: 'DevOpsProject',
    metadata: {
      name: item.name,
      generateName: item.name,
      origin: 'Gitlab',
      creationTimestamp: item.created_at,
      visibility: item.visibility,
      description: item.description,
      annotations: {
        'devopsproject.devops.kubesphere.io/syncstatus': 'successful',
      },
      labels: {
        'kubesphere.io/workspace': item.name.split('/')[0],
      },
    },
  }))

  ctx.body = {
    items,
    totalItems: items.length,
  }
}

module.exports = {
  getUserProjects,
}
